import React, { Component } from 'react';
import { Form,Button,Row,Col } from 'antd';
import { getDistance } from 'ol/sphere';
import { FormElement,ModalContent } from 'ra-lib';
import config from 'src/commons/config-hoc';
import Map from 'src/components/map';
import { EnvironmentOutlined } from '@ant-design/icons';

@config({
    ajax: true,
    modal: {
        title: props => props.isEdit ? '修改' : '添加',
    },
})
export default class EditModal extends Component {
    state = {
        loading: false, // 页面加载loading
        data: {},       // 回显数据
    };

    componentDidMount() {
        const { children,itemData } = this.props;

        if(children)this.$map.updateLocation({location:itemData.location?itemData.location.split(','):null})
    }

    fetchData = () => {
        if (this.state.loading) return;

        const { id } = this.props;

        this.setState({ loading: true });
        this.props.ajax.get(`/mock/users/${id}`)
            .then(res => {
                this.setState({ data: res });
                this.form.setFieldsValue(res);
            })
            .finally(() => this.setState({ loading: false }));
    };

    handleSubmit = (values) => {
        if (this.state.loading) return;
        const { isEdit } = this.props;
        let ajaxMethod = isEdit ? this.props.ajax.put : this.props.ajax.post;
        let ajaxApi = isEdit ? '/api/update' : '/api/add';
        let successTip = isEdit ? '修改成功！' : '添加成功！';
        values.children = values.children ? values.children :[];

        const {type, id,itemData } = this.props;
        if(type === 'addstop'){
            const {busstop,dist,location,orderNum} = values;
            let distLast = 0
            if(itemData.children.length>0){
                console.log(location);
                console.log(itemData.children[itemData.children.length - 1].location,"==");
                let la = location.split(',');
                let lb = itemData.children[itemData.children.length-1].location.split(',')
                distLast = getDistance(la,lb).toFixed(2);
            }
            console.log(distLast,"距离");
            itemData.children.push({busstop,dist:distLast+'m', location,orderNum})
            ajaxMethod = this.props.ajax.put;
             ajaxApi = '/api/update';
             successTip = '添加成功！';
            values = itemData
        }
        if(type === 'edit'){
            ajaxMethod = this.props.ajax.put;
            ajaxApi = '/api/update';
            successTip = '修改成功！';
            itemData.name = values.name;
            values = itemData;
        }

        if(type === 'editstop'){
            const {index, id,itemData,dataSource,tableChinIndex } = this.props;
            ajaxMethod = this.props.ajax.put;
            ajaxApi = '/api/update';
            successTip = '修改成功！';
            let datat =null;
            let datatindex =0;
            for (let i = 0; i <dataSource.length ; i++) {
                if(dataSource[i].id == id){
                    datat = dataSource[i];
                    datatindex = index;
                    break;
                }
            }
            datat.children.forEach(item=>item.id = '')
            let distLast = 0;
            if(tableChinIndex>0){
                let la = values.location.split(',');
                let lb = datat.children[tableChinIndex].location.split(',')
                distLast = getDistance(la,lb).toFixed(2);
            }
            console.log(distLast,"距离");
            datat.children[tableChinIndex].busstop = values.busstop;
            datat.children[tableChinIndex].dist = distLast+'m';
            datat.children[tableChinIndex].location = values.location;
            datat.children[tableChinIndex].orderNum = values.orderNum;
            values = datat;
        }



        this.setState({ loading: true });
        ajaxMethod(ajaxApi, values, { successTip })
            .then(() => {
                const { onOk } = this.props;
                onOk && onOk();
            })
            .finally(() => this.setState({ loading: false }));
    };

    render() {
        const { isEdit,children,itemData } = this.props;
        const { loading, data } = this.state;
        const formProps = {
            labelWidth: 100,
        };
        return (
            <ModalContent
                loading={loading}
                okText="保存"
                cancelText="重置"
                onOk={() => this.form.submit()}
                onCancel={() => this.form.resetFields()}
            >
                <Form
                    ref={form => this.form = form}
                    onFinish={this.handleSubmit}
                    initialValues={itemData}
                >
                    {isEdit ? <FormElement {...formProps} type="hidden" name="id" /> : null}
                    {
                        children?<>
                            <FormElement
                                {...formProps}
                                label="站點名稱"
                                name="busstop"
                                required
                                noSpace
                            />
                            {/*<FormElement*/}
                            {/*    {...formProps}*/}
                            {/*    label="距离"*/}
                            {/*    name="dist"*/}
                            {/*    required*/}
                            {/*    noSpace*/}
                            {/*/>*/}
                            <FormElement
                                {...formProps}
                                label="排序"
                                type="number"
                                name="orderNum"
                                required
                                noSpace
                            />
                            <FormElement
                                {...formProps}
                                label="位置"
                                name="location"
                                required
                                noSpace

                            />
                            <Map
                                childEvevnt={map=>this.$map = map}
                                getLocation={(location)=>{
                                    // 获取更新后坐标
                                    this.form.setFieldsValue({location:location.join(',')});

                                }}
                            />
                        </>:<FormElement
                            {...formProps}
                            label="公交"
                            name="name"
                            required
                            noSpace
                        />
                    }
                </Form>
            </ModalContent>
        );
    }
}

